#include "vc.h"
#include "cw32l011_vc.h"
#include "adc.h"

uint16_t  gFlagIrq = FALSE;

void vc_init(void)
{
    VC_InitTypeDef VC_InitStruct;
    VC_BlankTypeDef VC_BlankStruct;
    VC_DivTypeDef VC_DivStruct;

    __SYSCTRL_VC_CLK_ENABLE();
    //电阻分压配置
    
    VC_DivStruct.VC_DivVref = VC_DivVref_VDDA;
    VC_DivStruct.VC_DivEn = VC_Div_Enable;  
    VC_DivStruct.VC_DivValue = 7;
    VC1VC2_DIVInit(&VC_DivStruct);//DIV初始化
    //VC通道初始化
    VC_InitStruct.VC_InputP = VC_InputP_Ch1;
    VC_InitStruct.VC_InputN = VC_InputN_DivOut;//电阻分压
    VC_InitStruct.VC_Hys = VC_Hys_Off;//没有迟滞
    VC_InitStruct.VC_Resp = VC_Resp_High;
    VC_InitStruct.VC_FilterClk = VC_FltClk_PCLK;
    VC_InitStruct.VC_FilterTime = VC_FilterTime_4N6;
    VC_InitStruct.VC_Window = VC_Window_Disable;
    VC_InitStruct.VC_Polarity = VC_Polarity_High;
    VC1_ChannelInit(&VC_InitStruct);
    VC1VC2_INNInit(&VC_InitStruct);//负端输入信号初始化;


    //VC Blank窗口初始化
    VC1VC2_BlankInit(&VC_BlankStruct);
    VC_BlankStruct.VC_BlankLevel = VC_BlankLevel_high ;
    VC_BlankStruct.VC_BlankTime = VC_BlankTime_512Clk ;
    VC_BlankStruct.VC_BlankCh5 = VC_BlankCh4_Enable ;
    VC1_BlankCfg(&VC_BlankStruct);
    //VC中断设置
    VC1_ITConfig(VC_IT_HIGH, ENABLE);
    VC1_EnableIrq(VC_INT_PRIORITY);
    VC1_ClearIrq();
    VC1_EnableChannel();
}
/**
 * @brief Set the overcurr value object
 * 
 * @param threshhold 过流阈值
 */
void vc_set_overcurr_value(uint16_t threshhold)
{
    uint16_t vref_adc,vref;
    uint16_t v1;
    int i;
    uint16_t vdda = vdda_calibration();
    vref_adc = get_Vref_sampled_value();//运放参考电压adc值
    vref = vref_adc * vdda/4095;
    //把过流值转换成电压     v1 = threshhold * 0.005 * 50
    v1 = threshhold / 4;
    v1 += vref;
    for ( i = 1; i < 8; i++)
    {
        if((i*vdda / 8) > v1)
        {
            break;
        }
    }
    if (i <= 0x08)
    {
        CW_VCDIV->DIV_f.DIV = i-1;
    }
    //
}
